package it.rockliveitalia;

import it.rockliveitalia.database.EventDbHelper;
import it.rockliveitalia.entity.Event;
import it.rockliveitalia.tool.NsMenuAdapter;
import it.rockliveitalia.tool.NsMenuItemModel;
import it.rockliveitalia.tool.Parser;
import it.rockliveitalia.tool.Sender;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.xml.sax.SAXException;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MapActivity extends ActionBarActivity implements
		GooglePlayServicesClient.ConnectionCallbacks,
		GooglePlayServicesClient.OnConnectionFailedListener,
		OnMarkerClickListener {

	protected final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
	protected GoogleMap googleMap;
	protected Location location;
	protected LocationClient mLocationClient;
	protected Marker myMarker;
	protected List<Event> eventList = new ArrayList<Event>();
	protected List<Marker> markers = new ArrayList<Marker>();
	protected Context context;
	protected static String[] eventDetails = new String[13];
	protected boolean refresh = false;
	protected EditText search;
	protected Button searchButton;
	protected boolean setup;
	protected boolean fileLoaded;
	protected boolean otherFilesLoaded;
	protected boolean noLocation = false;
	protected boolean network_enabled = false;
	protected boolean googlePlayServices = true;

	protected ListView mDrawerList;
	protected DrawerLayout mDrawer;
	protected CustomActionBarDrawerToggle mDrawerToggle;
	protected String[] menuItems;
	protected LocationManager lm = null;
	protected boolean firstTime;
	protected SharedPreferences prefs;
	protected Date date;
	protected List<File> fileList;
	protected AlertDialog alert;
	protected AsyncTask<Void, Void, String> as;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_map);
		context = this.getApplicationContext();

		// enable ActionBar app icon to behave as action to toggle nav drawer
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);

		mDrawer = (DrawerLayout) findViewById(R.id.activity_map);
		initMenu();
		mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
		mDrawer.setDrawerListener(mDrawerToggle);
		search = (EditText) findViewById(R.id.map_search);
		searchButton = (Button) findViewById(R.id.search_button);
		// Getting Google Play availability status
		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getBaseContext());

		// Showing status
		if (status != ConnectionResult.SUCCESS) { // Google Play Services are
			// not available
			search.setVisibility(View.GONE);
			searchButton.setVisibility(View.GONE);
			// int requestCode = 10;
			// Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
			// this,
			// requestCode);
			// dialog.show();
			googlePlayServices = false;

		} else { // Google Play Services are available
			fileLoaded = getIntent().getBooleanExtra("fileLoaded", true);
			setup = getIntent().getBooleanExtra("setup", false);

			getMap();

			mLocationClient = new LocationClient(this, this, this);
			firstTime = true;
			refresh = false;

			if (!fileLoaded) {
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setTitle(R.string.network_error_title);
				dialog.setMessage(R.string.events_not_available);
				dialog.setNeutralButton(R.string.retry,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// User clicked details button
								Intent intent = new Intent(context,
										SetupMapActivity.class);

								startActivity(intent);
							}
						});
				dialog.setIcon(R.drawable.ic_dialog_alert_holo_dark);

				if (alert != null) {
					if (alert.isShowing()) {
						alert.dismiss();
					}
				}
				alert = dialog.create();
				alert.show();

			} else {
				if (setup)
					setSupportProgressBarIndeterminateVisibility(true);
				download();
			}

			EventDbHelper help = new EventDbHelper(this);
			Cursor c = help.getEvents();
			eventList = help.cursorToEvents(c);
			help.close();
			drawMarker(eventList);
			googleMap.setOnMarkerClickListener(this);
		}

	}

	protected void download() {
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String dateString = prefs.getString("lastDownload",
				getString(R.string.initial_date));
		boolean first = prefs.getBoolean("firstTime", true);
		Event e = new Event();
		e.setDate(dateString);
		final Sender s = new Sender();
		date = e.getDate();
		fileList = s.createFile(this, date, first);

		try {
			as = new AsyncTask<Void, Void, String>() {
				@Override
				public String doInBackground(Void... arg) {
					String lastDownload = null;

					try {
						lastDownload = s.download(fileList, date);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return lastDownload;
				}

				@Override
				protected void onPostExecute(String result) {
					updateEvents(fileList, result);
					setSupportProgressBarIndeterminateVisibility(false);
				}

				private void updateEvents(List<File> list, String result) {

					Parser p = new Parser();
					EventDbHelper helper = new EventDbHelper(context);
					List<Event> tempList = new ArrayList<Event>();
					boolean flag = false;
					for (File file : list) {
						try {
							tempList.addAll(p.parseXml(file));
						} catch (SAXException e) {
							e.printStackTrace();
							flag = true;
						}
					}
					for (Event e : tempList) {
						helper.insertEvent(e);
					}
					SharedPreferences.Editor editor = prefs.edit();

					if (result != null) {
						if (!result.equals("NoConnection") && !flag) {
							if (result.equals("todayFile")) {
								otherFilesLoaded = true;
							} else {
								editor.putString("lastDownload", result);
								editor.commit();
								otherFilesLoaded = true;
							}
						} else {
							otherFilesLoaded = false;
						}
					} else {
						otherFilesLoaded = false;
					}
					if (!otherFilesLoaded) {
						AlertDialog.Builder dialog = new AlertDialog.Builder(
								MapActivity.this);
						dialog.setTitle(R.string.network_error_title);
						dialog.setMessage(R.string.event_error);
						dialog.setNegativeButton(R.string.go_on,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										otherFilesLoaded = true;
									}
								});
						dialog.setNeutralButton(R.string.retry,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// User clicked details button
										Intent intent = new Intent(context,
												SetupMapActivity.class);

										startActivity(intent);
									}
								});
						dialog.setIcon(R.drawable.ic_dialog_alert_holo_dark);

						if (alert != null) {
							if (alert.isShowing()) {
								alert.dismiss();
							}
						}
						alert = dialog.create();
						alert.show();

					}
					Cursor c = helper.getEvents();
					eventList = helper.cursorToEvents(c);
					drawMarker(eventList);
				}
			}.execute();

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}

	protected void initMenu() {
		NsMenuAdapter mAdapter = new NsMenuAdapter(this);

		// Add Header
		mAdapter.addHeader(R.string.ns_menu_main_header);

		// Add first block
		menuItems = getResources().getStringArray(R.array.ns_menu_items);
		String[] menuItemsIcon = getResources().getStringArray(
				R.array.ns_menu_items_icon);

		int res = 0;
		for (String item : menuItems) {

			int id_title = getResources().getIdentifier(item, "string",
					this.getPackageName());
			int id_icon = getResources().getIdentifier(menuItemsIcon[res],
					"drawable", this.getPackageName());

			NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
			mAdapter.addItem(mItem);
			res++;
		}

		mDrawerList = (ListView) findViewById(R.id.drawer);
		if (mDrawerList != null)
			mDrawerList.setAdapter(mAdapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.navigation_refresh).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {

		public CustomActionBarDrawerToggle(Activity mActivity,
				DrawerLayout mDrawerLayout) {
			super(mActivity, mDrawerLayout, R.drawable.ic_drawer,
					R.string.app_name, R.string.app_name);
		}

		@Override
		public void onDrawerClosed(View view) {
			getSupportActionBar().setTitle(getTitle().toString());
			supportInvalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
		}

		@Override
		public void onDrawerOpened(View drawerView) {
			getSupportActionBar().setTitle(getString(R.string.app_name));
			supportInvalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
		}
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			switch (position) {
			case 1: {
				myClass();
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 2: {
				todayEvents();
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 3: {
				Intent intent = new Intent(context, EventFilterActivity.class);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 4: {
				Intent intent = new Intent(context, InputFormActivity.class);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 5: {
				Intent intent = new Intent(context, StringListActivity.class);
				intent.putExtra("mode", 0);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 6: {
				Intent intent = new Intent(context, StringListActivity.class);
				intent.putExtra("mode", 1);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 7: {
				Intent intent = getOpenFacebookIntent(context);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 8: {
				Intent intent = getOpenTwitterIntent(context);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 9: {
				Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
						"mailto", "rockliveitalia@gmail.com", null));
				intent.putExtra(Intent.EXTRA_SUBJECT, "Suggerimento");
				startActivity(Intent.createChooser(intent, "Invio e-mail"));
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 10: {
				Uri uri = Uri.parse("market://details?id="
						+ context.getPackageName());
				Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(goToMarket);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			case 11: {
				Intent intent = new Intent(context, InformationActivity.class);
				startActivity(intent);
				mDrawer.closeDrawer(mDrawerList);
				break;
			}
			}
		}
	}

	protected void todayEvents() {
		Calendar cal = Calendar.getInstance();
		Event e = new Event();
		e.setDate(cal.getTime());
		String date = e.getStringDate();
		EventDbHelper helper = new EventDbHelper(context);
		List<Event> list = helper.cursorToEvents(helper.getEvents());
		List<String> ids = dateFilter(list, date);
		if (ids.size() == 0) {
			AlertDialog.Builder alertb = new AlertDialog.Builder(
					MapActivity.this);
			alertb.setTitle(R.string.no_result_title);
			alertb.setPositiveButton(R.string.ok, null);
			alertb.setMessage(R.string.no_event_message);
			alertb.setIcon(R.drawable.ic_alerts_and_states_error);
			AlertDialog alert = alertb.create();
			alert.show();
		} else {
			Intent intent = new Intent(context, MapFilterActivity.class);
			intent.putStringArrayListExtra("ids", (ArrayList<String>) ids);
			intent.putExtra("filter", date);
			startActivity(intent);
		}
	}

	protected List<String> dateFilter(List<Event> list, String s) {
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			Event e = list.get(i);
			if (e.getStringDate().equals(s)) {
				result.add(e.getId());
			}
		}
		return result;
	}

	protected void myClass() {
		refresh = true;
		checkConnection();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		// Handle presses on the action bar items
		switch (item.getItemId()) {

		case R.id.navigation_refresh: {
			refresh = true;
			checkConnection();
		}
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private static Intent getOpenFacebookIntent(Context context) {

		try {
			context.getPackageManager()
					.getPackageInfo("com.facebook.katana", 0);
			return new Intent(Intent.ACTION_VIEW,
					Uri.parse("fb://page/594637220566978"));
		} catch (Exception e) {
			return new Intent(Intent.ACTION_VIEW,
					Uri.parse("https://touch.facebook.com/rockliveit"));
		}
	}

	private static Intent getOpenTwitterIntent(Context context) {
		try {
			context.getPackageManager()
					.getPackageInfo("com.twitter.android", 0);
			return new Intent(Intent.ACTION_VIEW,
					Uri.parse("twitter://user?screen_name=rockliveit"));
		} catch (Exception e) {
			return new Intent(Intent.ACTION_VIEW,
					Uri.parse("https://mobile.twitter.com/rockliveit"));
		}
	}

	public void search(View view) {
		String s = search.getText().toString();
		if (!s.equals("")) {
			InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			in.hideSoftInputFromWindow(search.getApplicationWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
			try {
				moveCamera(s);

			} catch (IndexOutOfBoundsException e) {
				Toast.makeText(this, R.string.address_not_found,
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} catch (IOException e) {
				Toast.makeText(this, R.string.service_unavailable,
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		} else {
			Toast.makeText(this, R.string.no_address, Toast.LENGTH_SHORT)
					.show();
		}
	}

	protected void getMap() {
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
		googleMap = fm.getMap();
	}

	protected void drawMarker(List<Event> list) {
		for (Marker m : markers) {
			if (m != null) {
				m.remove();
			}
		}
		markers = new ArrayList<Marker>();
		if (list != null) {
			for (Event e : list) {
				LatLng ll = new LatLng(Double.parseDouble(e.getLat()),
						Double.parseDouble(e.getLng()));
				MarkerOptions mOption = new MarkerOptions();
				if (e.getTag().equals("g")) {
					BitmapDescriptor icon = BitmapDescriptorFactory
							.fromResource(R.drawable.guitargoldpointer);
					mOption.icon(icon);
				} else if (e.getTag().equals("b")) {
					BitmapDescriptor icon = BitmapDescriptorFactory
							.fromResource(R.drawable.guitarbluepointer);
					mOption.icon(icon);
				} else {
					BitmapDescriptor icon = BitmapDescriptorFactory
							.fromResource(R.drawable.guitarbluepointer);
					mOption.icon(icon);
				}
				mOption = mOption.position(ll);
				markers.add(googleMap.addMarker(mOption));
			}
		} else {
			Toast.makeText(this, R.string.markers_error, Toast.LENGTH_SHORT)
					.show();
		}
	}

	protected void checkConnection() {
		if (lm == null)
			lm = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
		try {
			network_enabled = lm
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
		}
		if (fileLoaded) {
			if (!network_enabled && !noLocation) {
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setTitle(R.string.network_not_enabled_title);
				dialog.setMessage(context.getResources().getString(
						R.string.network_not_enabled));
				dialog.setPositiveButton(R.string.active,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface paramDialogInterface,
									int paramInt) {
								// TODO Auto-generated method stub
								Intent myIntent = new Intent(
										Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								context.startActivity(myIntent);
							}
						});
				dialog.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface paramDialogInterface,
									int paramInt) {
								// TODO Auto-generated method stub
								noLocation = true;
								moveCameraItaly();
							}

						});
				dialog.setIcon(R.drawable.ic_dialog_alert_holo_dark);

				if (alert != null) {
					if (alert.isShowing()) {
						alert.dismiss();
					}
				}
				alert = dialog.create();
				alert.show();

			} else if (!isOnline()) {
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setTitle(R.string.network_error_title);
				dialog.setMessage(R.string.network_error);
				dialog.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// User clicked OK button
							}
						});
				dialog.setIcon(R.drawable.ic_dialog_alert_holo_dark);

				if (alert != null) {
					if (alert.isShowing()) {
						alert.dismiss();
					}
				}
				alert = dialog.create();
				alert.show();

			}
		}
		if (googlePlayServices) {
			mLocationClient.connect();
		}
	}

	protected void moveCameraItaly() {
		CameraPosition pos = new CameraPosition(
				new LatLng(42.504503, 12.678223), 5, 0, 0);
		CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(pos);
		googleMap.animateCamera(cameraUpdate);
	}

	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
		// TODO Auto-generated method stub
		/*
		 * Google Play services can resolve some errors it detects. If the error
		 * has a resolution, try sending an Intent to start a Google Play
		 * services activity that can resolve error.
		 */
		if (connectionResult.hasResolution()) {
			try {
				// Start an Activity that tries to resolve the error
				connectionResult.startResolutionForResult(this,
						CONNECTION_FAILURE_RESOLUTION_REQUEST);
				/*
				 * Thrown if Google Play services canceled the original
				 * PendingIntent
				 */
			} catch (IntentSender.SendIntentException e) {
				// Log the error
				e.printStackTrace();
			}
		} else {
			/*
			 * If no resolution is available, display a dialog to the user with
			 * the error.
			 */
			Toast.makeText(this, connectionResult.getErrorCode(),
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
		checkConnection();
	}

	@Override
	public void onConnected(Bundle arg0) {
		geolocation();
	}

	protected void geolocation() {
		location = mLocationClient.getLastLocation();
		LatLng latLng = null;
		if (firstTime || refresh) {
			try {
				latLng = new LatLng(location.getLatitude(),
						location.getLongitude());

				MarkerOptions mOption = new MarkerOptions();
				mOption = mOption.position(latLng);
				BitmapDescriptor icon = BitmapDescriptorFactory
						.fromResource(R.drawable.homepointer);
				mOption.icon(icon);
				if (myMarker != null) {
					myMarker.remove();
				}
				myMarker = googleMap.addMarker(mOption);
				moveCamera(latLng);

			} catch (NullPointerException e) {
				moveCameraItaly();
				if (!network_enabled) {
					Toast.makeText(this, R.string.location_needed,
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.no_location,
							Toast.LENGTH_SHORT).show();
				}
				e.printStackTrace();
			}
			firstTime = false;
			refresh = false;
		}

	}

	protected void moveCamera(LatLng latLng) {
		CameraPosition pos = new CameraPosition(latLng, 11, 0, 0);
		CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(pos);
		googleMap.animateCamera(cameraUpdate);
	}

	@Override
	public boolean onMarkerClick(final Marker marker) {
		List<Event> markerEvents = new ArrayList<Event>();
		int myIndex = 0;
		if (markers.contains(marker)) {
			boolean found = false;
			for (int i = 0; i < markers.size() && !found; i++) {
				if (markers.get(i).equals(marker)) {
					myIndex = i;
					found = true;
				}
			}
			for (int j = 0; j < eventList.size(); j++) {
				if (eventList.get(myIndex).getVenueName()
						.equals(eventList.get(j).getVenueName())) {
					markerEvents.add(eventList.get(j));
				}
			}
			AlertDialog.Builder alertb = new AlertDialog.Builder(this);

			if (markerEvents.size() > 0) {
				alertb.setTitle(markerEvents.get(0).getVenueName());
				List<String> strings = new ArrayList<String>();
				for (int e = 0; e < markerEvents.size(); e++) {
					strings.add(markerEvents.get(e).getStringDate() + ": "
							+ markerEvents.get(e).getBand());
				}
				final List<Event> events = markerEvents;
				final CharSequence[] items = strings.toArray(new String[strings
						.size()]);
				alertb.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// The 'which' argument contains the
						// index position
						// of the selected item
						eventDetails = getEventDetails(events.get(which));
						Intent intent = new Intent(context, EventActivity.class);
						intent.putExtra("eventDetails", eventDetails);
						startActivity(intent);
					}
				});
				alertb.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// User clicked OK button
							}
						});
				alertb.setIcon(R.drawable.ic_location_place);
				AlertDialog alert = alertb.create();
				alert.show();
			}

		}
		return true;
	}

	private String[] getEventDetails(Event event) {
		String[] details = new String[13];

		details[0] = String.valueOf(event.getId());
		details[1] = event.getVenueName();
		details[2] = event.getVenueSite();
		details[3] = event.getStringDate();
		details[4] = event.getStreet();
		details[5] = event.getCity();
		details[6] = event.getProvincia();
		details[7] = event.getBand();
		details[8] = event.getBandSite();
		details[9] = event.getDescription();
		details[10] = event.getImage();
		details[11] = event.getLat();
		details[12] = event.getLng();

		return details;
	}

	protected String getAddress(Context context, Location location)
			throws IOException {
		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addresses = gc.getFromLocation(location.getLatitude(),
				location.getLongitude(), 1);
		return addresses.get(0).getAddressLine(0);

	}

	protected void moveCamera(String loc) throws IOException {
		Geocoder geocoder = new Geocoder(this, Locale.getDefault());
		List<Address> addresses = geocoder.getFromLocationName(loc, 1);
		LatLng latLng = new LatLng(addresses.get(0).getLatitude(), addresses
				.get(0).getLongitude());
		refresh = false;
		moveCamera(latLng);
	}

	@Override
	protected void onStop() {
		// Disconnecting the client invalidates it.
		// mLocationClient.disconnect();
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);

	}

	@Override
	public void onDisconnected() {
		Toast.makeText(this, R.string.network_error_disconnected,
				Toast.LENGTH_SHORT).show();
	}

	protected boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	public void navigationRefresh(View view) {
		checkConnection();
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (as != null) {
			as.cancel(false);
		}
		if (fileList != null) {
			for (File file : fileList) {
				file.delete();
			}
		}
		// mLocationClient.disconnect();
	}

}
